package com.warrior.superdata.dds.esclient;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class RestClientTimer {

    /**
     * 默认超时时间
     */
    private static long idel = 5 * 60 * 1000;

    private ElasticsearchRestClient restClient;

    private long lastUpdateTime = 0L;

    /**
     * 构造函数
     *
     * @param restClient
     */
    public RestClientTimer(ElasticsearchRestClient restClient) {
        this.restClient = restClient;
        this.lastUpdateTime = System.currentTimeMillis();
    }

    /**
     * 刷新更新时间
     */
    public void refreshTime() {
        lastUpdateTime = System.currentTimeMillis();
    }

    /**
     * 检查超时连接并关闭
     *
     * @return
     */
    public boolean checkAndClose() {
        try{
            if (isTimeout()) {
                if(null != restClient.getRestHighLevelClient()){
                    restClient.getRestHighLevelClient().close();
                    restClient.setRestClientBuilder(null);
                    restClient = null;
                }
                return true;
            }
        }catch (Exception e){
            log.error("========== 关闭RestHighLevelClient异常 errMsg:{} =========",e.getMessage());
        }
        return false;
    }

    /**
     * 判断是否超时
     *
     * @return
     */
    private boolean isTimeout() {
        return (System.currentTimeMillis() - lastUpdateTime) > idel;
    }
}
